package service

import (
	"strconv"
	"zzxq/models"
	"zzxq/repository/userrepository"
)

type User struct {
}

//登录获取
func (a *User) UserLogin(phone string, code string) (*models.User, bool) {
	//1.校验验证码
	smsobj := &Sms{}
	realCode := smsobj.GLoginCode(phone)
	if realCode == "" && realCode != code {
		return nil, false
	}

	//2.验证码正确获取或者创建用户
	dbobj := &userrepository.DBUser{}
	user := dbobj.UserLogin(phone)

	return user, true
}

//根据uid获取用户信息
func (a *User) GetUserInfo(uid int) *models.User {
	var user models.User

	//处理是否设置用户信息缓存
	redisobj := &userrepository.RedisUser{}
	mapuser := redisobj.GetAllUserInfo(uid)

	if len(mapuser) == 0 {
		//从数据库获取信息并返回
		dbobj := &userrepository.DBUser{}
		user = dbobj.GetUserInfo(uid)

		if user.Uid != 0 {
			redisobj.SetUsrinfo(uid, map[string]interface{}{
				"uid":      user.Uid,
				"phone":    user.Phone,
				"nickname": user.Nickname,
				"avatar":   user.Avatar,
				"status":   user.Status,
				"sex":      user.Sex,
				"age":      user.Age,
				"role":     user.Role,
				"password": user.Password,
				"ctime":    user.Ctime,
				"utime":    user.Utime,
			})
		}
	} else {
		mapuid, _ := strconv.Atoi(mapuser["uid"])
		mapstatus, _ := strconv.Atoi(mapuser["status"])
		mapsex, _ := strconv.Atoi(mapuser["sex"])
		user = models.User{
			Uid:      mapuid,
			Phone:    mapuser["phone"],
			Nickname: mapuser["nickname"],
			Avatar:   mapuser["avatar"],
			Status:   mapstatus,
			Sex:      mapsex,
			Password: mapuser["password"],
			Ctime:    mapuser["ctime"],
			Utime:    mapuser["utime"],
		}
	}

	return &user
}
